/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mediatek.datatransfer.view;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Outline;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tecno.widget.Toast;

import com.mediatek.datatransfer.R;
import com.mediatek.datatransfer.R.color;
import com.mediatek.datatransfer.R.drawable;

/**
 * Lightweight implementation of ViewPager tabs. This looks similar to traditional actionBar tabs,
 * but allows for the view containing the tabs to be placed anywhere on screen. Text-related
 * attributes can also be assigned in XML - these will get propogated to the child TextViews
 * automatically.
 */
public class ViewPagerTabs extends HorizontalScrollView implements ViewPager.OnPageChangeListener {

    ViewPager mPager;
    private ViewPagerTabStrip mTabStrip;

    /**
     * Linearlayout that will contain the TextViews serving as tabs. This is the only child
     * of the parent HorizontalScrollView.
     */
    final int mTextStyle;
    ColorStateList mTextColor;
    final int mTextSize;
    final boolean mTextAllCaps;
    int mPrevSelected = -1;
    int mSidePadding;
    //add by qiankun.gong for OS Contacts;
    float mDefaultScalePercent =0.9f;
    float mMaxScalePercent = 1.0f;
    private int mSelctR;
    private int mSelctG;
    private int mSelctB;
    
    private int mUnSelctR;
    private int mUnSelctG;
    private int mUnSelctB;
    private int mUnSelctA = 127;

    private static final ViewOutlineProvider VIEW_BOUNDS_OUTLINE_PROVIDER =
            new ViewOutlineProvider() {
        @Override
        public void getOutline(View view, Outline outline) {
            outline.setRect(0, 0, view.getWidth(), view.getHeight());
        }
    };

    private static final int TAB_SIDE_PADDING_IN_DPS = 10;

    // TODO: This should use <declare-styleable> in the future
    private static final int[] ATTRS = new int[] {
        android.R.attr.textSize,
        android.R.attr.textStyle,
        android.R.attr.textColor,
        android.R.attr.textAllCaps
    };

    /**
     * Simulates actionbar tab behavior by showing a toast with the tab title when long clicked.
     */
    private class OnTabLongClickListener implements OnLongClickListener {
        final int mPosition;

        public OnTabLongClickListener(int position) {
            mPosition = position;
        }

        @Override
        public boolean onLongClick(View v) {
        	//D HIOSWY-2837 by huan.yang 20151111@{
        	/*
        	final int[] screenPos = new int[2];
            getLocationOnScreen(screenPos);

            final Context context = getContext();
            final int width = getWidth();
            final int height = getHeight();
            final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
            
            Toast toast = Toast.makeText(context, mPager.getAdapter().getPageTitle(mPosition),
                    Toast.LENGTH_SHORT);
            
            // Show the toast under the tab
            toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
                    (screenPos[0] + width / 2) - screenWidth / 2, screenPos[1] + height);

            toast.show(); 
            */
          //D HIOSWY-2837 by huan.yang 20151111@}         
            return true;
            
        }
    }

    public ViewPagerTabs(Context context) {
        this(context, null);
    }

    public ViewPagerTabs(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ViewPagerTabs(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFillViewport(true);

        mSidePadding = (int) (getResources().getDisplayMetrics().density * TAB_SIDE_PADDING_IN_DPS);

        final TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
        mTextSize = a.getDimensionPixelSize(0, 0);
        mTextStyle = a.getInt(1, 0);
        mTextColor = a.getColorStateList(2);
        mTextAllCaps = a.getBoolean(3, false);
        
        //add by qiankun.gong for OS Contacts
        getSelectColorHex(getResources().getColor(R.color.viewpager_select_tilte_color));
        setUnSelectColorHex(getResources().getColor(R.color.viewpager_unselect_tilte_color));

        mTabStrip = new ViewPagerTabStrip(context);
        addView(mTabStrip,
                new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        a.recycle();

        // enable shadow casting from view bounds
        setOutlineProvider(VIEW_BOUNDS_OUTLINE_PROVIDER);
    }

    public void setViewPager(ViewPager viewPager) {
        mPager = viewPager;
        addTabs(mPager.getAdapter());
    }

    private void addTabs(PagerAdapter adapter) {
        mTabStrip.removeAllViews();

        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            addTab(adapter.getPageTitle(i), i);
        }
    }

    private void addTab(CharSequence tabTitle, final int position) {
        final TextView textView = new TextView(getContext());
        textView.setText(tabTitle);
        textView.setBackground(null);
        //rlk add meng.wu WSHBLL-1395 20160420 (start)
        int mBomPadding = (int) (getResources().getDisplayMetrics().density * 5);
        textView.setSingleLine();
        //rlk add meng.wu WSHBLL-1395  20160420 (end)
        //textView.setBackgroundResource(R.drawable.view_pager_tab_background);
        textView.setGravity(Gravity.CENTER);
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	int prePosition = mPager.getCurrentItem();
            	int pos = getRtlPosition(position);
                mPager.setCurrentItem(pos);
				if(mListener != null){
					mListener.doTabTextClick(true,prePosition, pos);
				}
            }
        });

        textView.setOnLongClickListener(new OnTabLongClickListener(position));

        // Assign various text appearance related attributes to child views.
        if (mTextStyle > 0) {
            textView.setTypeface(textView.getTypeface(), mTextStyle);
        }
        if (mTextSize > 0) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        }
        if (mTextColor != null) {
            textView.setTextColor(mTextColor);
        }
        textView.setAllCaps(mTextAllCaps);
        textView.setPadding(mSidePadding, 0, mSidePadding, mBomPadding);
        textView.setGravity(Gravity.CENTER);
        mTabStrip.addView(textView, new LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT, 1));
        // Default to the first child being selected
        if (position == 0) {
            mPrevSelected = 0;
            textView.setSelected(true);
            //add by qiankun.gong for OS Contacts
            textView.setTextColor(Color.argb(255, mSelctR, mSelctG, mSelctB));
        } else {
        	textView.setTextColor(Color.argb(mUnSelctA, mUnSelctR, mUnSelctG, mUnSelctB));
        }
        initTitleSize(textView,mDefaultScalePercent);
    }
    /*
     * update the ViewPager Tips background color
     */
    public void setTabStripBg(int color){
    	mTabStrip.setBackgroundColor(color);
    }
    public void setTabStripColor(ColorStateList textColor,int mPaintColor){
    	mTextColor = textColor;
    	mTabStrip.setUnderlinePaintColor(mPaintColor);
    	getSelectColorHex(mPaintColor);
    }
	private void getSelectColorHex(int selectColor){
		mSelctR = (0x00FF0000 & selectColor) >> 16;
		mSelctG = (0x0000FF00 & selectColor) >> 8;	
		mSelctB = 0x000000FF & selectColor;
	}
	public void setUnSelectColorHex(int unSelectColor){
		mUnSelctR = (0x00FF0000 & unSelectColor) >> 16;
		mUnSelctG = (0x0000FF00 & unSelectColor) >> 8;	
		mUnSelctB = 0x000000FF & unSelectColor;
	}
	public void setSelectedTextColor(int positon){
		TextView selectView =  (TextView) mTabStrip.getChildAt(positon);
		if(selectView != null){
			selectView.setTextColor(Color.argb(255, mSelctR, mSelctG, mSelctB));
		}
	}
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        position = getRtlPosition(position);
        int tabStripChildCount = mTabStrip.getChildCount();
        if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
            return;
        }
        //modify by qiankun.gong for OS Contacts
        mTabStrip.onPageScrolled(position, positionOffset, positionOffsetPixels,mPrevSelected);
        if(positionOffset > 0){
        	if(mPrevSelected == 0 && position == 0){ //0-1
        		setGrayTitleColor(mTabStrip.getChildAt(0),positionOffset);
        		setHightLightTitleColor(mTabStrip.getChildAt(1),positionOffset);
        	}else if(mPrevSelected == 1 && position == 0){ //1-0
        		setGrayTitleColor(mTabStrip.getChildAt(1),1-positionOffset);
        		setHightLightTitleColor(mTabStrip.getChildAt(0),1-positionOffset);
            }else if(mPrevSelected == 1 && position == 1){ //1-2
            	setGrayTitleColor(mTabStrip.getChildAt(1),positionOffset);
        		setHightLightTitleColor(mTabStrip.getChildAt(2),positionOffset);
            }else if(mPrevSelected == 2 && position == 1){ //2-1
            	setGrayTitleColor(mTabStrip.getChildAt(2),1-positionOffset);
        		setHightLightTitleColor(mTabStrip.getChildAt(1),1-positionOffset);
            }
        	setTitleSize(mTabStrip.getChildAt(position),1-positionOffset);
        	setTitleSize(mTabStrip.getChildAt(position + 1),positionOffset);
        }
    }

    @Override
    public void onPageSelected(int position) {
        position = getRtlPosition(position);
        int tabStripChildCount = mTabStrip.getChildCount();
        if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
            return;
        }
        if (mPrevSelected >= 0 && mPrevSelected < tabStripChildCount) {
            mTabStrip.getChildAt(mPrevSelected).setSelected(false);
            //add by qiankun.gong for OS Contacts
            ((TextView) mTabStrip.getChildAt(mPrevSelected)).setTextColor(Color.argb(mUnSelctA, mUnSelctR, mUnSelctG, mUnSelctB));
        }
        final View selectedChild = mTabStrip.getChildAt(position);
        selectedChild.setSelected(true);
        //add by qiankun.gong for OS Contacts
        ((TextView) selectedChild).setTextColor(Color.argb(255, mSelctR, mSelctG, mSelctB));
        initTitleSize( ((TextView) selectedChild),mMaxScalePercent);

        // Update scroll position
        final int scrollPos = selectedChild.getLeft() - (getWidth() - selectedChild.getWidth()) / 2;
        smoothScrollTo(scrollPos, 0);
        mPrevSelected = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    private int getRtlPosition(int position) {
    	/*delete by qiankun.gong for OS Contacts
        if (getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            return mTabStrip.getChildCount() - 1 - position;
        }*/
        return position;
    }
    /*
     * author qiankun.gong
     * Change the textColor of view
     */
    private void setGrayTitleColor(View view,float mOffset){
    	if(view == null) return;
    	
    	int r = (int) Math.ceil(mSelctR + (mOffset*(mUnSelctR-mSelctR)));
    	int g =(int) Math.ceil(mSelctG +(mOffset*(mUnSelctG-mSelctG)));
    	int b = (int) Math.ceil(mSelctB - (mOffset*(mSelctB-mUnSelctB)));

    	if(mSelctR < mUnSelctR){
    		if(r > mUnSelctR){
        		r = mUnSelctR ;
        	}
    	}else{
    		if(r < mUnSelctR){
        		r = mUnSelctR ;
        	}
    	}
    	
    	if(mSelctG < mUnSelctG){
    	    
        	if(g > mUnSelctG){
        		g = mUnSelctG ;
        	}
    	}else{  	    
        	if(g < mUnSelctG){
        		g = mUnSelctG ;
        	}
    	}
    	
    	if(mSelctB < mUnSelctB){  	
        	if(b > mUnSelctB){
        		b = mUnSelctB ;
        	}
    	}else{      	
        	if(b < mUnSelctB){
        		b = mUnSelctB ;
        	}
    	}
    	((TextView) view).setTextColor(Color.argb(255, r, g, b));
    }
    /*
     * author qiankun.gong
     * Change the textColor of view
     */
    private void setHightLightTitleColor(View view,float mOffset){
    	if(view == null) return;
    	
    	int r = (int) Math.ceil(mUnSelctR - (mOffset*(mUnSelctR-mSelctR)));
    	int g =(int) Math.ceil(mUnSelctG - (mOffset*(mUnSelctG-mSelctG)));
    	int b = (int) Math.ceil(mUnSelctB + (mOffset*(mSelctB-mUnSelctB)));
    	if(mSelctR < mUnSelctR){
        	if(r < mSelctR){
        		r = mSelctR ;
        	}
    	}else{
    		if(r > mSelctR){
        		r = mSelctR ;
        	}
    	}
    	
    	if(mSelctG < mUnSelctG){
        	if(g < mSelctG){
        		g = mSelctG ;
        	}
    	}else{
        	if(g > mSelctG){
        		g = mSelctG ;
        	}
    	}
    	
    	if(mSelctB < mUnSelctB){
        	if(r < mSelctB){
        		r = mSelctB ;
        	}
    	}else{
        	if(b > mSelctB){
        		b = mSelctB ;
        	}
    	}
    	((TextView) view).setTextColor(Color.argb(mUnSelctA, r, g, b));
    }
    /*
     * author qiankun.gong
     * ZoomIn or ZoomOut the view
     */
    private void setTitleSize(View view,float mSize){
    	float size = mSize*(mMaxScalePercent-mDefaultScalePercent) + mDefaultScalePercent;
    	if(size < mDefaultScalePercent){
    		size = mDefaultScalePercent;
    	}
    	if(size > mMaxScalePercent){
    		size = mMaxScalePercent;
    	}
    	PropertyValuesHolder animatorY = PropertyValuesHolder.ofFloat("scaleY", 1.0f, size);
    	PropertyValuesHolder animatorX = PropertyValuesHolder.ofFloat("scaleX", 1.0f, size);
		ObjectAnimator.ofPropertyValuesHolder(view, animatorY,animatorX).setDuration(0).start();
    }
    private void initTitleSize(View view,float size){
    	PropertyValuesHolder animatorY = PropertyValuesHolder.ofFloat("scaleY", 1.0f, size);
    	PropertyValuesHolder animatorX = PropertyValuesHolder.ofFloat("scaleX", 1.0f, size);
		ObjectAnimator.ofPropertyValuesHolder(view, animatorY,animatorX).setDuration(0).start();
    }
    /*
     * @add a interface to callBack the onclick event.
     * to control the bottomMenu's animation
     */
    private onTabTextClickListener mListener;
    public interface onTabTextClickListener{
    	void doTabTextClick(boolean isClick,int currentPosition, int nextPosition);
    }
    public void setTabTextClickListener(onTabTextClickListener listener){
    	mListener = listener;
    }
}

